<?php

namespace Simanx\Spes\Middlewares;

use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\DB;

class Transaction
{
    private const IGNORE_REQUEST_METHOD = ['HEAD', 'GET', 'OPTIONS'];

    public function handle(Request $request, \Closure $next)
    {
        if (in_array($request->method(), static::IGNORE_REQUEST_METHOD)) {
            return $next($request);
        }

        DB::beginTransaction();
        try {
            /** @var Response $response */
            $response = $next($request);
            if ($response->exception) {
                DB::rollBack();
            } else {
                DB::commit();
            }

            return $response;
        } catch (\Exception $exception) {
            DB::rollBack();
        }
    }
}